package com.study.sync;

/**
 * @Author HBZ
 * @Date 2020/8/16 22:58
 * @Description synchronized (this){} 作用的范围是大括号{}括起来的代码，作用的对象是调用这个代码块的对象
 */
public class SyncThread2 implements Runnable{
    private static int count;
    public SyncThread2() {
        count = 0;
    }
    @Override
    public  void run() {
        synchronized (this){
            for (int i = 0; i < 5; i++) {
                try {
                    System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public int getCount() {
        return count;
    }

    public static void main(String[] args) {
        System.out.println("使用关键字synchronized");
        SyncThread2 syncThread = new SyncThread2();
        Thread thread1 = new Thread(syncThread, "SyncThread1");
        Thread thread2 = new Thread(syncThread, "SyncThread2");
        thread1.start();
        thread2.start();
    }
}
